﻿Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page
    'Brandon Maroney
    'User Home Page
    'This page that you are taken to after login, this page's purpose is to show basic user info
    'display quizzes created(and who has taken them), and quizzes taken(and the corresponding grade)

    Private connectionString As String = WebConfigurationManager.ConnectionStrings("Database").ConnectionString

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            userNameHiddenField.Value = CType(PreviousPage.FindControl("userNameHiddenField"), HiddenField).Value
            nameLabel.Text = userNameHiddenField.Value
            getUserID(nameLabel.Text)
            userNameHiddenField.Value = nameLabel.Text
            fillQuizzesCreatedListBox(sender, e)
            deleteQuizButton.Visible = False
        End If

        'Possibly use previouspage.[] to get user information for name
        'or set hidden field on login page with user id, then get that value from hidden field to get name,rank,id from tables with corresponding id
    End Sub

    Private Sub fillQuizzesCreatedListBox(ByVal sender As Object, ByVal e As System.EventArgs)
        quizzesCreatedListBox.Items.Clear()
        Dim selectSQL As String = "SELECT * FROM QuestionMain WHERE OwnerID = '" & userIDHiddenField.Value & "'"
        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(selectSQL, myConnection)
        Dim myAdapter As New SqlDataAdapter(myCommand)
        Dim quizDataset As New DataSet()

        Try
            myConnection.Open()
            myAdapter.Fill(quizDataset, "QuestionMain")
            For Each row As DataRow In quizDataset.Tables("QuestionMain").Rows
                Dim newItem As New ListItem
                newItem.Text = row("quizTitle")
                newItem.Value = row("Quiz_Id").ToString
                quizzesCreatedListBox.Items.Add(newItem)
            Next
        Catch ex As Exception
            errorLabel.Text = "Error getting your created quizzes. " & ex.Message
        Finally
            myConnection.Close()
        End Try

    End Sub

    'Protected Sub fillQuizTakersListBox(ByVal sender As Object, ByVal e As System.EventArgs)
    '    Dim selectSQL As String = "SELECT *  FROM QuizTaken WHERE quizTaken_Id = '" & quizzesCreatedListBox.SelectedValue & "'"
    '    Dim myConnection As New SqlConnection(connectionString)
    '    Dim myCommand As New SqlCommand(selectSQL, myConnection)
    '    Dim myAdapter As New SqlDataAdapter(myCommand)
    '    Dim quizDataSet As New DataSet

    '    Try
    '        myConnection.Open()
    '        myAdapter.Fill(quizDataSet, "QuizTaken")
    '        For Each row As DataRow In quizDataSet.Tables("QuizTaken").Rows
    '            Dim newItem As New ListItem
    '            newItem.Text = row("userName")
    '            newItem.Value = row("User_Id").ToString
    '            quizTakenByListBox.Items.Add(newItem)
    '        Next
    '    Catch ex As Exception
    '        errorLabel.Text = "Error getting users who've taken selected quiz. " & ex.Message
    '    Finally
    '        myConnection.Close()
    '    End Try
    'End Sub

    Protected Sub quizzesCreatedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles quizzesCreatedListBox.SelectedIndexChanged
        errorLabel.Text = ""
        'fillQuizTakersListBox(sender, e)
    End Sub

    Protected Sub createQuizButton_Click(sender As Object, e As EventArgs) Handles createQuizButton.Click
        Dim successBoolean As Boolean = True
        Dim insertSQL As New StringBuilder
        insertSQL.Append("INSERT INTO QuestionMain(OwnerID,DateTime,quizTitle)")
        insertSQL.Append("VALUES (@OwnerID,@DateTime,@quizTitle)")

        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(insertSQL.ToString, myConnection)

        With myCommand.Parameters
            .AddWithValue("@OwnerID", userIDHiddenField.Value.ToString)
            .AddWithValue("@DateTime", DateAndTime.Now.ToString)
            .AddWithValue("@quizTitle", "No Title Entered".ToString)
        End With

        Try
            myConnection.Open()
            successBoolean = myCommand.ExecuteNonQuery
        Catch ex As Exception
            successBoolean = False
            errorLabel.Text = "Error going to page " & ex.Message
        Finally
            myConnection.Close()
        End Try
        quizHiddenField.Value = "1"
    End Sub

    Protected Sub deleteQuizPopUp_Click(sender As Object, e As EventArgs) Handles deleteQuizPopUp.Click
        deleteQuizButton.Visible = True
    End Sub

    Protected Sub deleteQuizButton_Click(sender As Object, e As EventArgs) Handles deleteQuizButton.Click
        errorLabel.Text = ""
        deleteQuizButton.Visible = False
        Dim deleteQuizSQL As String
        deleteQuizSQL = "DELETE FROM QuestionMain WHERE Quiz_Id=@Quiz_Id"
        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(deleteQuizSQL, myConnection)

        myCommand.Parameters.AddWithValue("@Quiz_Id", quizzesCreatedListBox.SelectedValue)

        Dim successQuizBoolean As Boolean = True
        Dim successQuestionBoolean As Boolean = True

        Try
            myConnection.Open()
            successQuizBoolean = myCommand.ExecuteNonQuery
            errorLabel.Text = "Quiz Deleted"
            deleteQuizButton.Visible = False

            Dim deleteQuestionsSQL As String
            deleteQuestionsSQL = " DELETE FROM QuestionSelect WHERE Quiz_Id=@Quiz_Id"
            errorLabel.Text = "Quiz Deleted"
            Try
                successQuizBoolean = myCommand.ExecuteNonQuery
                deleteQuizButton.Visible = False
            Catch ex As Exception
                successQuestionBoolean = False
                errorLabel.Text = "Error deleting questions. " & ex.Message
            End Try

        Catch ex As Exception
            successQuizBoolean = False
            errorLabel.Text = "Error deleting quiz. " & ex.Message
        Finally
            myConnection.Close()
        End Try

        If successQuizBoolean Or successQuestionBoolean Then
            fillQuizzesCreatedListBox(sender, e)
            quizzesCreatedListBox_SelectedIndexChanged(sender, e)
        End If
    End Sub

    Protected Sub quizzesCreatedListBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles quizzesCreatedListBox.SelectedIndexChanged
        errorLabel.Text = ""
    End Sub

    Protected Sub getUserID(ByVal username As String)
        Dim getIDSQL As New StringBuilder
        getIDSQL.Append("SELECT * FROM userTable WHERE UserName = '" & username & "'")
        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(getIDSQL.ToString, myConnection)
        Dim myReader As SqlDataReader
        Try
            myConnection.Open()
            myReader = myCommand.ExecuteReader
            myReader.Read()
            userIDHiddenField.Value = myReader("User_Id")
        Catch ex As Exception
            errorLabel.Text = "Cant get User ID" & ex.Message
            Response.Redirect("~/Default.aspx")
        Finally
            myConnection.Close()
        End Try
    End Sub

    Protected Sub logOutButton_Click(sender As Object, e As EventArgs) Handles logOutButton.Click
        Dim oldCookie As HttpCookie = Request.Cookies("getLogin")
        If oldCookie IsNot Nothing Then
            oldCookie.Expires = DateAndTime.Now.AddDays(-1D)
            Response.Cookies.Add(oldCookie)
        End If
        Response.Redirect("~/Default.aspx")
    End Sub

    Protected Sub updateQuiz_Click(sender As Object, e As EventArgs) Handles updateQuiz.Click
        If quizzesCreatedListBox.SelectedValue = "" Then

        Else
            titleHiddenField.Value = quizzesCreatedListBox.SelectedItem.ToString
            quizIDHiddenField.Value = quizzesCreatedListBox.SelectedValue
            quizHiddenField.Value = ""
        End If

    End Sub



    Protected Sub takeQuizButton_Click(sender As Object, e As EventArgs) Handles takeQuizButton.Click
        quizIDHiddenField.Value = quizzesCreatedListBox.SelectedValue
        getUserID(nameLabel.Text)
    End Sub
End Class





'This is where you will display which users have taken your quiz
'errorLabel.Text = ""
'Dim selectSQL As String = "SELECT UserName, User_Id FROM userTable WHERE userTable.User_Id = QuizTaken.User_Id AND QuizTaken.quizTaken_Id ='" & quizzesCreatedListBox.SelectedItem.Value & "'"
'Dim myConnection As New SqlConnection(connectionString)
'Dim myCommand As New SqlCommand(selectSQL, myConnection)
'Dim myReader As SqlDataReader

'Try
'    myConnection.Open()
'    myReader = myCommand.ExecuteReader
'    Do While myReader.Read
'        Dim newItem As New ListItem
'        newItem.Text = myReader("UserName")
'        newItem.Value = myReader("User_Id").ToString
'        quizTakenByListBox.Items.Add(newItem)
'    Loop
'    myReader.Close()
'Catch ex As Exception
'    errorLabel.Text = "Error getting the users who have taken your quiz " & ex.Message
'Finally
'    myConnection.Close()
'End Try